# 乳腺癌预测
import numpy as np
from matplotlib import pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
import torch
from torch import nn
from torch.nn import functional as F

# 准备数据
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
mean_ = X_train.mean(axis=0)
std_ = X_train.std(axis=0)
print(mean_.shape)
print(X_test.shape)
X_train = (X_train - mean_)/std_
X_test = (X_test - mean_)/std_


class MyDataset(Dataset):

    def __init__(self, X,y):
        self.X = X
        self.y = y

    def __getitem__(self, idx):
        x = self.X[idx]
        y = self.y[idx]
        return torch.tensor(x).float(), torch.tensor(y).long()

    def __len__(self):
        return len(self.X)


train_dataset = MyDataset(X=X_train, y=y_train)
train_dataloader = DataLoader(dataset=train_dataset, batch_size=32, shuffle=True, drop_last=True)
test_dataset = MyDataset(X=X_test, y=y_test)
test_dataloader = DataLoader(dataset=test_dataset, batch_size=32, shuffle=True, drop_last=False)

# 准备模型


class LinearRegression(nn.Module):

    def __init__(self, in_features, out_features):
        super(LinearRegression, self).__init__()
        self.linear1 = nn.Linear(in_features=in_features, out_features=out_features)

    def forward(self, x):
        out = self.linear1(x)
        return out


lr = LinearRegression(in_features=30, out_features=2)

# 模型训练
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(params=lr.parameters(), lr=1e-2)  # 11.10


def get_loss(dataloader=train_dataloader, model=lr, loss_fn=loss_fn):
    with torch.no_grad():
        losses = []
        for X,y in dataloader:
            loss = loss_fn(model(X), y)
            losses.append(loss)
        return sum(losses)/len(losses)


def get_acc(dataloader=train_dataloader, model=lr, loss_fn=loss_fn):
    with torch.no_grad():
        accs = []
        